﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using DTC.Popups;
using DTC.Database;

namespace DTC.Pages
{
    /// <summary>
    /// Interaction logic for MedRecordsListPage.xaml
    /// </summary>
    public partial class MedRecordsListPage : Page
    {
        public MedRecordsListPage()
        {
            InitializeComponent();
            patients = new ObservableCollection<DTCPatient>(App.DBI.GetAllPatiens());
            MedRecListBox.ItemsSource = patients;
            UsualSort();

        }
        private ICollectionView view;

        private ObservableCollection<DTCPatient> patients;

        public void AddPatient(DTCPatient newPatient)
        {
            patients.Add(newPatient);
        }

        private void DoctorGroupCheckBox_Click(object sender, RoutedEventArgs e)
        {
            if (MedRecListBox.ItemsSource != null)
            {
                if (view.GroupDescriptions.Count != 0)
                    view.GroupDescriptions.RemoveAt(0);
                view.GroupDescriptions.Add(new PropertyGroupDescription("DTCDoctor.FullName"));
            }
        }

        private void DiseaseGroupRadioButton_Click(object sender, RoutedEventArgs e)
        {
            if (MedRecListBox.ItemsSource != null)
            {
                if (view.GroupDescriptions.Count != 0)
                    view.GroupDescriptions.RemoveAt(0);
                view.GroupDescriptions.Add(new PropertyGroupDescription("DTCDisease.Code"));
            }
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            if (MedRecListBox.ItemsSource != null)
            {
                string[] tmpStrSet = SearchStringTextBox.Text.Trim().Split(new char[] { ' ' });
                string tmpstr;
                SearchString = new Collection<string>();
                foreach (string str in tmpStrSet)
                {
                    tmpstr = str.Trim();
                    if (str.Length != 0)
                        SearchString.Add(tmpstr);
                }
                ListCollectionView view = (ListCollectionView)
                    CollectionViewSource.GetDefaultView(MedRecListBox.ItemsSource);
                view.Filter = new Predicate<object>(FilterRecs);
            }

        }
        Collection<string> SearchString;
        private bool FilterRecs(Object item)
        {
            //search done here
            if (SearchString.Count == 0) 
                return true;
            
            if (item is DTCPatient)
            {
                bool matches = true;
                bool foundsub;
                DTCPatient pat = item as DTCPatient;
                foreach (string substring in SearchString)
                {
                    foundsub = false;
                    if (substring == pat.PatientNumber)
                        foundsub = true;
                    else if (substring == pat.Surname)
                        foundsub = true;
                    else if (substring == pat.Name)
                        foundsub = true;
                    else if (substring == pat.Fathername)
                        foundsub = true;
                    else if (pat.DTCDisease != null)
                    {
                        if (substring == pat.DTCDisease.Code)
                            foundsub = true;
                        else if (substring == pat.DTCDisease.Name)
                            foundsub = true;
                    }
                    if (!foundsub)
                    {
                        matches = false; 
                        break;
                    }
                }
                return matches;
                       
            }
            return false;
        }

        private void NoGoupingRadioButton_Click(object sender, RoutedEventArgs e)
        {
            if (view.GroupDescriptions.Count != 0)
                view.GroupDescriptions.RemoveAt(0);
        }

        private void UsualSort()
        {
            if (MedRecListBox.ItemsSource != null)
            {
                view = CollectionViewSource.GetDefaultView(MedRecListBox.ItemsSource);
                view.SortDescriptions.Add(
                  new SortDescription("PatientNumber", ListSortDirection.Ascending));
                view.SortDescriptions.Add(
                  new SortDescription("DTCDisease.Code", ListSortDirection.Ascending));
                view.SortDescriptions.Add(
                  new SortDescription("Surname", ListSortDirection.Ascending));
                view.SortDescriptions.Add(
                  new SortDescription("Name", ListSortDirection.Ascending));
                view.SortDescriptions.Add(
                  new SortDescription("Fathername", ListSortDirection.Ascending));
            }
        }

        private void DelRecord_Click(object sender, RoutedEventArgs e)
        {
            Button cmd = (Button)sender;
            DTCPatient pat = (DTCPatient)cmd.Tag;
            ConfirmationPopup cp = new ConfirmationPopup();
            cp.TitleText = "Необходимо подтверждение";
            cp.Message = "Вы уверены в том, что хотите удалить пациента " + pat.FullName + " из базы данных?";
            if (cp.ShowDialog() == true)
            {
                pat.Delete();
                MedRecListBox.SelectedIndex = -1;
                patients.Remove(pat);
            }
        }
        

        private void AddRecord_Click(object sender, RoutedEventArgs e)
        {
            MedicalRecordPopup mrp = new MedicalRecordPopup();
            mrp.Owner = App.Current.MainWindow;
            if (mrp.ShowDialog() == true)
            {
                patients.Add(mrp.Patient);
            }
        }

        private void ViewRecord_Click(object sender, RoutedEventArgs e)
        {
            Button cmd = (Button)sender;
            DTCPatient pat = (DTCPatient)cmd.Tag;
            MedicalRecordPopup mrp = new MedicalRecordPopup();
            mrp.Owner = App.Current.MainWindow;
            mrp.Patient = pat;
            mrp.ShowDialog();
            MedRecListBox.Items.Refresh();
        }

        private void ViewVisits_Click(object sender, RoutedEventArgs e)
        {
            DTCPatient pt;
            try
            {
                pt = GetPatientFromFrameworkElement((FrameworkElement)e.OriginalSource);
            }
            catch
            {
                return;
            }
            if (pt != null)
            {
                VisitsHistoryPopup vhp = new VisitsHistoryPopup();
                vhp.Patient = pt;
                vhp.Owner = App.Current.MainWindow;
                vhp.ShowDialog();
            }
        }

        private void ViewDrugPrescs_Click(object sender, RoutedEventArgs e)
        {
            DTCPatient pt;
            try
            {
                pt = GetPatientFromFrameworkElement((FrameworkElement)e.OriginalSource);
            }
            catch
            {
                return;
            }
            if (pt != null)
            {
                PatientDrugPrescriptionListPopup pdpl = new PatientDrugPrescriptionListPopup();
                pdpl.Patient = pt;
                pdpl.Owner = App.Current.MainWindow;
                pdpl.ShowDialog();
            }
        }

        private DTCPatient GetPatientFromFrameworkElement(FrameworkElement fe)
        {
            DTCPatient pt;
            try
            {
                
                while (!(fe is ListBoxItem))
                    fe = (FrameworkElement)fe.TemplatedParent;
                ListBoxItem pat = fe as ListBoxItem;
                pt = (DTCPatient)pat.DataContext;
                //set listbox selection to pressed button parent
                MedRecListBox.SelectedItem = pt;
            }
            catch
            {
                throw new NullReferenceException();
            }
            return pt;
        }

    }
}
